package com.ezandroid.util;

import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.graphics.Point;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;

import java.util.Locale;

/**
 * 应用程序工具类.
 *
 * @author markmjw
 * @date 2014-08-17
 */
public final class AppUtil {

    private static final String TAG = "AppUtil";

    private static String sAndroidId;
    private static String sVersion;
    private static String sImei;
    private static String mReqDeviceId;
    private static Point sPoint;

    /**
     * 系统
     *
     * @return
     */
    public static String getOS() {
        return "Android";
    }

    /**
     * 系统版本号
     *
     * @return
     */
    public static String getOSVersion() {
        return Build.VERSION.RELEASE;
    }

    /**
     * 设备名称
     *
     * @return
     */
    public static String getDevice() {
        return Build.MODEL;
    }

    /**
     * 设备唯一标示
     *
     * @return MD5(IMEI + android_id)
     */
    public static String getDeviceId(Context context) {
        if (TextUtils.isEmpty(mReqDeviceId)) {
            final StringBuilder gDidSb = new StringBuilder();
            String imei = getIMEI(context);
            if (!TextUtils.isEmpty(imei)) {
                gDidSb.append(imei);
            }

            String android_id = getAndroidId(context);
            if (!TextUtils.isEmpty(android_id)) {
                gDidSb.append(android_id);
            }

            mReqDeviceId = Util.encrypt(gDidSb.toString(), "MD5");
        }
        return mReqDeviceId;
    }

    /**
     * 获取androidId.
     *
     * @return
     */
    public static String getAndroidId(Context context) {
        if (TextUtils.isEmpty(sAndroidId)) {
            sAndroidId = Secure.getString(context
                    .getContentResolver(), Secure.ANDROID_ID);
        }
        return sAndroidId;
    }

    /**
     * 获取程序版本号.
     *
     * @return empty string if failed
     */
    public static String getAppVersion(Context context) {
        if (TextUtils.isEmpty(sVersion)) {
            try {
                sVersion = context.getPackageManager().getPackageInfo(context.getPackageName(),
                        0).versionName;
            } catch (Throwable e) {
                LogUtil.e(TAG, "Get application version name failed! error: " + e.getMessage());
                sVersion = "1.0";
            }
        }
        return sVersion;
    }

    /**
     * 获取IMEI值.
     *
     * @return empty string if failed
     */
    public static String getIMEI(Context context) {
        if (TextUtils.isEmpty(sImei)) {
            try {
                sImei = ((TelephonyManager) (context.getSystemService(Context.TELEPHONY_SERVICE)))
                        .getDeviceId();
            } catch (Throwable e) {
                sImei = "";
                LogUtil.e(TAG, "Get IMEI failed! error: " + e.getMessage());
            }
        }
        return sImei;
    }

    /**
     * 获取本地Mac地址.
     *
     * @param context the context
     * @return empty string if failed
     */
    public static String getMacAddress(Context context) {
        String macAdress = null;
        try {
            WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

            WifiInfo info = wifi.getConnectionInfo();

            macAdress = info.getMacAddress();
        } catch (Throwable e) {
            LogUtil.e(TAG, "Get mac address failed! error: " + e.getMessage());
        }
        return macAdress == null ? "" : macAdress;
    }

    /**
     * 通过包名来检查一个应用是否存在.
     *
     * @param context     the context
     * @param packageName the package name
     * @return true, if successful
     */
    public static boolean checkApplicationExist(Context context, String packageName) {
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            context.getPackageManager().getApplicationInfo(packageName,
                    PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (NameNotFoundException e) {
            return false;
        }
    }

    /**
     * 运营商
     *
     * @param context
     * @return
     */
    public static String getCarrier(Context context) {
        TelephonyManager manager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        return manager.getNetworkOperatorName();
    }

    /**
     * 语言、国家
     *
     * @return
     */
    public static String getLocale() {
        Locale locale = Locale.getDefault();
        return locale.getLanguage() + "_" + locale.getCountry();
    }

    /**
     * 获取屏幕尺寸
     *
     * @param context
     * @return
     */
    public static Point getScreenSize(Context context) {
        if (null == sPoint) {
            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

            sPoint = new Point();
            wm.getDefaultDisplay().getSize(sPoint);
        }
        return sPoint;
    }

    /**
     * 获取分辨率
     *
     * @return
     */
    public static String getResolution(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);

        Display display = wm.getDefaultDisplay();

        DisplayMetrics metrics = new DisplayMetrics();
        display.getMetrics(metrics);

        return metrics.heightPixels + "x" + metrics.widthPixels;
    }

    /**
     * 是否为竖屏
     *
     * @param context
     * @return
     */
    public static boolean isPortrait(Context context) {
        Configuration configuration = context.getResources().getConfiguration();
        int ori = configuration.orientation;

        return ori == Configuration.ORIENTATION_PORTRAIT || ori != Configuration.ORIENTATION_LANDSCAPE;
    }
}
